package org.nicocube.airain.domain.server.dao;

import java.util.HashMap;
import java.util.Map;

import javax.jdo.PersistenceManager;

import org.nicocube.airain.domain.client.exception.DomainException;

public class DomainDAO {

	private static Map<Class<? extends DomainDAO>,DomainDAO> daoSet = new HashMap<Class<? extends DomainDAO>, DomainDAO>();
	
	protected void eval(DomainRequest ... requests) throws DomainException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			PersistenceAccessor accessor = new PersistenceAccessor(pm);
			for (DomainRequest rq : requests) rq.playOn(accessor);
		} finally {
			pm.close();
		}
	}

	public static <T extends DomainDAO> T getDao(Class<T> clazz) {
		if (!daoSet.containsKey(clazz)) {
			try {
				daoSet.put(clazz, clazz.newInstance());
			} catch (InstantiationException e) {
				throw new IllegalStateException(e.getMessage(),e);
			} catch (IllegalAccessException e) {
				throw new IllegalStateException(e.getMessage(),e);
			}
		}
		return clazz.cast(daoSet.get(clazz));
	}
}
